#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <pthread.h>

static void * (*real_malloc)(size_t size) = NULL;
static void (*real_free)(void *ptr) = NULL;

void * malloc(size_t size) {
    pid_t tid = syscall(SYS_gettid);
    pid_t pid = getpid();
    fprintf(stderr, "my malloc: %s %zu pid:%d tid:%d\n", __TIME__, size, pid, tid);
    // use dlsym to find next malloc in dynamic libraries, ie. malloc in std library
    real_malloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc");
    return real_malloc(size);
}

void free(void *ptr) {
	if(!ptr) return;
    pid_t tid = syscall(SYS_gettid);
    pid_t pid = getpid();
    fprintf(stderr,"my free: %s %p pid:%d tid:%d\n", __TIME__, ptr, pid, tid);
    real_free = (void (*)(void *))dlsym(RTLD_NEXT, "free");
    real_free(ptr);
}
